<template>
	<a-modal
		:title="type == ORDER_TYPE_ENUM.inOrder.id ? '入库' : type == ORDER_TYPE_ENUM.outOrder.id ? '出库' : type == ORDER_TYPE_ENUM.purchaseOrder.id ? '提交采购' : ''"
		:width="1400" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading" @ok="handleSubmit"
		@cancel="handleCancel">

		<a-spin :spinning="confirmLoading">
			<a-form :form="form">
				<a-row>

					<a-col :span="12" v-show="false">
						<a-form-item label="订单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入订单类型"
								v-decorator="['orderType', { rules: [{ required: true, message: '请输入订单类型！' }] }]" />
						</a-form-item>
					</a-col>

					<!-- <a-col :span="24">
            <a-form-item
              label="供应商"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback="">
              <a-radio-group button-style="solid" v-model="orgIdSupplier">
                <a-radio-button :value="id" v-for="{id, name} in supplierList">
                  {{ name }}
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col> -->

					<a-col :span="24" v-show="false">
						<a-table ref="table" size="default" style="margin-bottom: 24px" :columns="columns"
							:data-source="filteredData" :pagination="false">
						</a-table>
					</a-col>

					<a-col :span="24">
						<a-form-item
							:label="type == ORDER_TYPE_ENUM.inOrder.id ? '入库单号' : type == ORDER_TYPE_ENUM.outOrder.id ? '出库单号' : type == ORDER_TYPE_ENUM.purchaseOrder.id ? '采购单号' : ''"
							:labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入单号"
								v-decorator="['orderNumber', { rules: [{ required: true, message: '请输入单号' }] }]" />
						</a-form-item>
					</a-col>
					<a-col :span="24">
						<a-form-item label="备注" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入备注"
								v-decorator="['remark', { rules: [{ required: false, message: '请输入备注！' }] }]" />
						</a-form-item>
					</a-col>
					<a-col :span="24" v-if="type == ORDER_TYPE_ENUM.outOrder.id">
						<a-form-item label="生产单号" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入生产单号"
								v-decorator="['parentNumber', { rules: [{ required: false, message: '请输入单号' }] }]" />
						</a-form-item>
					</a-col>
					<a-col :span="13" v-if="poolType == ORDER_TYPE_ENUM.purchaseOrder.id">
						<a-form-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<span style="font-weight: bold;">{{
								filteredData.length ? filteredData[0].orgIdSupplierName : '--'
							}}</span>
						</a-form-item>
					</a-col>

					<!-- 采购池 -->
					<template v-if="type == ORDER_TYPE_ENUM.purchaseOrder.id">
						<!-- 采购池 且 主要供应商 -->
						<a-col :span="11" v-if="filteredData[0].isInvoice == 2">
							<a-form-item label="发票信息" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
								<div style="font-weight: bold;">
									发票类型：<span style="margin-right: 20px;">{{
										filteredData.length ? (filteredData[0].invoiceType == 1 ? '普票' :
											filteredData[0].invoiceType == 2 ? '专票' : '不需要发票') : '--'
									}}</span>
									税率：<span>{{
										filteredData.length && filteredData[0].taxRate ? filteredData[0].taxRate + '%' : '--'
									}}</span>
								</div>
							</a-form-item>
						</a-col>
						<!-- 采购池 且 普通供应商 -->
						<div v-if="filteredData[0].isInvoice == 1">
							<a-col :span="13">
								<a-form-item label="是否需要开票" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
									<a-radio-group v-decorator="['isInvoice', { rules: [{ required: true, message: '请选择！' }] }]"
										v-model="fcData.isInvoice" @change="() => {
											$set(fcData, 'invoiceType', undefined);
											$set(fcData, 'taxRate', undefined);
											form.setFieldsValue({ invoiceType: undefined, taxRate: undefined });
										}">
										<a-radio :value="1">不需要</a-radio>
										<a-radio :value="2">需要</a-radio>
									</a-radio-group>
								</a-form-item>
							</a-col>
							<!-- fcdata--{{ fcData }}
              form--{{ form.getFieldsValue() }} -->
							<a-col :span="11">
								<a-form-item label="发票类型" v-if="fcData.isInvoice === 2" :labelCol="labelCol" :wrapperCol="wrapperCol"
									has-feedback="">
									<a-radio-group v-decorator="['invoiceType', { rules: [{ required: true, message: '请选择！' }] }]"
										v-model="fcData.invoiceType"
										@change="() => { $set(fcData, 'taxRate', undefined); form.setFieldsValue({ taxRate: undefined }) }">
										<a-radio :value="1">普票</a-radio>
										<a-radio :value="2">专票</a-radio>
									</a-radio-group>
								</a-form-item>
							</a-col>
							<a-col :span="24">
								<a-form-item label="税率" v-if="fcData.isInvoice === 2" :labelCol="labelColBlock"
									:wrapperCol="wrapperColBlock" has-feedback="">
									<a-input-number
										v-decorator="['taxRate', { initialValue: undefined, rules: [{ required: true, message: '请输入！' }] }]"
										v-model="fcData.taxRate" placeholder="请输入" style="width: 100%" :min="0" :max="100" :precision="0" />
								</a-form-item>
							</a-col>
						</div>


						<a-col :span="24">
							<div>
								<a-button icon="add" type="primary"
									@click="$refs.selectMaterial.init(filteredData, materialType, poolType)">选择物料
								</a-button>
							</div>
							<a-table ref="table" size="default" :columns="columns" :data-source="filteredData" :pagination="false">
								<!-- 图片 -->
								<!-- <span slot="image" slot-scope="text">
								<image-preview :images="text" />
              </span> -->
								<span slot="image" slot-scope="text,record">
									<image-preview1 :images="text" :imageUrl="record.imageUrl" />
								</span>
								<!-- 采购数量 -->
								<span slot="buyNum" slot-scope="text, record">
									<a-input-number v-model="record.number" :min="1" style="width: 100%" />
								</span>
								<!-- 采购价 -->
								<span slot="buyPrice" slot-scope="text, record">
									<a-input-number v-model="record.purchasePrice" :min="0" style="width: 100%" />
								</span>
								<span slot="action" slot-scope="text, record, index">
									<a-popconfirm placement="topRight" title="确认删除？" @confirm="filteredData.splice(index, 1)">
										<a>删除</a>
									</a-popconfirm>
								</span>
							</a-table>
						</a-col>

					</template>

				</a-row>
			</a-form>
		</a-spin>
		<selectMaterial ref="selectMaterial" @selected="selected" />
	</a-modal>
</template>

<script>
import { addAllType, addSimple, page } from '@/api/modular/main/emsorder/emsOrderManage'
import { sysDictDataSupplierList } from '@/api/modular/main/emssysdictdata/emsDictDataManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import selectMaterial from './selectMaterial.vue'
import { STable } from '@/components'
import { list as emsOrgList } from '@/api/modular/main/emsorg/emsOrgManage'
import { getUrlParam, MATERIAL_TYPE_ENUM, ORDER_TYPE_ENUM } from '@/utils/util'

export default {
	components: { FcUpload, STable, selectMaterial },
	data() {
		return {
			fcData: {
				taxRate: undefined,
				isInvoice: undefined,
				invoiceType: undefined,
			},
			type: '',   //父组件传过来的id
			materialType: '',
			poolType: '',
			selectedList: [],
			labelCol: {
				xs: { span: 24 },
				sm: { span: 6 }
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 15 }
			},
			labelColBlock: {
				xs: { span: 24 },
				sm: { span: 3 }
			},
			wrapperColBlock: {
				xs: { span: 24 },
				sm: { span: 20 }
			},
			visible: false,
			confirmLoading: false,
			form: this.$form.createForm(this),
			fileList: [],
			orderMaterials: [],
			orgIdSupplier: 'all',
			// supplierList: [],
			columns: [       // 表头
				{
					title: '序号', width: '80px',
					dataIndex: 'index',
					customRender: (text, record, index) => `${index + 1}`
				},
				{
					title: '物料名称',
					dataIndex: 'materialName'
				},
				{
					title: '料号',
					dataIndex: 'materialCode'
				},
				{
					title: '规格',
					dataIndex: 'materialModelNumber'
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '库存',
					dataIndex: 'inventoryNumber'
				},
				{
					title: '采购数量',
					dataIndex: '',
					scopedSlots: { customRender: 'buyNum' }
				},
				{
					title: '采购价(含税价)',
					dataIndex: '',
					scopedSlots: { customRender: 'buyPrice' }
				},
				{
					title: '成本价(不含税)',
					dataIndex: '',
					// 如果是主要供应商,直接使用第0条数据中的税率,是否需要开票,发票类型字段
					// 如果是非主要供应商,使用fcData中的税率,是否需要开票,发票类型字段,并且根据选择的税率,计算税额,税后价,决定成本价和成本价小计的显示与否
					// 这里两个只是起显示作用,最终传给后端的数据是getCostPrice()方法计算出来的值
					customRender: (text, record, index) => {
						console.log("成本价(不含税)-", record);

						// 先判断是否开票 不开票：成本价=采购价。 isInvoice：1 = 不开票 ， 2 = 开票
						if (this.filteredData[0].isInvoice == 2) {
							// 再判断是专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票
							if (this.filteredData[0].invoiceType == 2) {
								return ((record.purchasePrice || 0) / (1 + (this.filteredData[0].taxRate) / 100)).toFixed(2)
							} else {
								return this.filteredData[0].purchasePrice.toFixed(2)
							}
						} else {
							// 如果是不开票先判断页面是否选择了开票 、isInvoice：1 = 不开票 ， 2 = 开票 （fcData.isInvoice：本地data的数据开票）
							if (this.fcData.isInvoice == 2) {
								// 再判断页面是否选择了专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票（fcData.invoiceType：本地data的数据发票类型）
								if (this.fcData.invoiceType == 2) {
									// 是专票的话看税率是否有值（fcData.taxRate：本地data的数据税率）
									if (this.fcData.taxRate) {
										return ((record.purchasePrice || 0) / (1 + (this.fcData.taxRate) / 100)).toFixed(2)
									} else {
										return '--'
									}
								} else {
									return this.filteredData[0].purchasePrice.toFixed(2)
								}
							} else {
								return this.filteredData[0].purchasePrice.toFixed(2)
							}
						}
						// if(this.filteredData&&this.filteredData[0].unitRanId=='1440879787235438593'){ //主要供应商
						// 	return ((record.purchasePrice||0) / (1 + (this.filteredData[0].taxRate&&this.filteredData[0].isInvoice==2&&this.filteredData[0].invoiceType==2 ? this.filteredData[0].taxRate : this.fcData.taxRate) / 100)).toFixed(2)
						//   // return ((record.purchasePrice||0) / (1 +  (this.fcData.taxRate&&this.fcData.isInvoice==2&&this.fcData.invoiceType==2 ? this.fcData.taxRate : 0) / 100)).toFixed(2)
						// } else if(
						// 	this.filteredData
						// 	&&this.filteredData[0].unitRanId=='1498270916314161153'
						// 	&&(this.fcData.isInvoice==1 || (this.fcData.isInvoice==2&&this.fcData.invoiceType==1) || (this.fcData.isInvoice==2&&this.fcData.invoiceType==2&&(this.fcData.taxRate||this.fcData.taxRate==0)))
						// ) { //非主要供应商
						// 	return ((record.purchasePrice||0) / (1 +
						// 	(this.fcData.taxRate&&this.fcData.isInvoice==2&&this.fcData.invoiceType==2 ? this.fcData.taxRate : 0)
						// 	/ 100)).toFixed(2)
						// } else {
						// 	return '--'
						// }
					}
				},
				{
					title: '成本价小计',
					customRender: (text, record, index) => {
						// 先判断是否开票 不开票：成本价=采购价。 isInvoice：1 = 不开票 ， 2 = 开票
						if (this.filteredData[0].isInvoice == 2) {
							// 再判断是专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票
							if (this.filteredData[0].invoiceType == 2) {
								return (((record.purchasePrice || 0) / (1 + (this.filteredData[0].taxRate) / 100)).toFixed(2) * record.number).toFixed(2)
							} else {
								return this.filteredData[0].purchasePrice.toFixed(2)
							}
						} else {
							// 如果是不开票先判断页面是否选择了开票 、isInvoice：1 = 不开票 ， 2 = 开票 （fcData.isInvoice：本地data的数据开票）
							if (this.fcData.isInvoice == 2) {
								// 再判断页面是否选择了专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票（fcData.invoiceType：本地data的数据发票类型）
								if (this.fcData.invoiceType == 2) {
									// 是专票的话看税率是否有值（fcData.taxRate：本地data的数据税率）
									if (this.fcData.taxRate) {
										return (((record.purchasePrice || 0) / (1 + (this.fcData.taxRate) / 100)).toFixed(2) * record.number).toFixed(2)
									} else {
										return '--'
									}
								} else {
									return this.filteredData[0].purchasePrice.toFixed(2)
								}
							} else {
								return this.filteredData[0].purchasePrice.toFixed(2)
							}
						}

						// if (this.filteredData && this.filteredData[0].unitRanId == '1440879787235438593') { //主要供应商
						//   return (((record.purchasePrice || 0) /
						//     (1 + (this.filteredData[0].taxRate && this.filteredData[0].isInvoice == 2 && this.filteredData[0].invoiceType == 2 ? this.filteredData[0].taxRate : 0) / 100)).toFixed(2) * record.number).toFixed(2)
						// } else if (
						//   this.filteredData
						//   && this.filteredData[0].unitRanId == '1498270916314161153'
						//   && (this.fcData.isInvoice == 1 || (this.fcData.isInvoice == 2 && this.fcData.invoiceType == 1) || (this.fcData.isInvoice == 2 && this.fcData.invoiceType == 2 && (this.fcData.taxRate || this.fcData.taxRate == 0)))
						// ) { //非主要供应商
						//   return (((record.purchasePrice || 0) / (1 + (this.fcData.taxRate && this.fcData.isInvoice == 2 && this.fcData.invoiceType == 2 ? this.fcData.taxRate : 0) / 100)).toFixed(2) * record.number).toFixed(2)
						// } else {
						//   return '--'
						// }
					}
				},
				{
					title: '操作',
					width: '100px',
					fixed: 'right',
					scopedSlots: { customRender: 'action' }
				}
			],
		}
	},
	computed: {
		ORDER_TYPE_ENUM() {
			return ORDER_TYPE_ENUM;
		},
		filteredData() {
			let orgIdSupplier = this.orgIdSupplier
			if (orgIdSupplier == 'all') {
				return this.orderMaterials
			}
			let filteredData
			if (orgIdSupplier == 'other') {
				let dictValues = this.supplierList.map(dict => dict.id)
				filteredData = this.orderMaterials.filter(value => {
					return dictValues.findIndex(value1 => value1 == value.orgIdSupplier) == -1
				})
			} else {
				filteredData = this.orderMaterials.filter(value => {
					return value.orgIdSupplier == orgIdSupplier
				})
			}
			console.log('过滤后的数据', filteredData)
			return filteredData
		},
		supplierList() {
			return this.$util.getOrgList([this.$businessEnum.ORG_TYPE_ENUM.PRIMARY_SUPPLIER.id, this.$businessEnum.ORG_TYPE_ENUM.NORMAL_SUPPLIER.id])
		}
	},
	methods: {
		resetFcData() {
			this.fcData = {
				taxRate: undefined,
				isInvoice: undefined,
				invoiceType: undefined,
			}
		},
		// 动态计算成本价
		getCostPrice(purchasePrice) {
			if (!this.filteredData[0]) {
				return
			}
			try {
				// 先判断是否开票 不开票：成本价=采购价。 isInvoice：1 = 不开票 ， 2 = 开票
				if (this.filteredData[0].isInvoice == 2) {
					// 再判断是专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票
					if (this.filteredData[0].invoiceType == 2) {
						return ((purchasePrice || 0) / (1 + (this.filteredData[0].taxRate) / 100)).toFixed(2)
					} else {
						return this.filteredData[0].purchasePrice.toFixed(2)
					}
				} else {
					// 如果是不开票先判断页面是否选择了开票 、isInvoice：1 = 不开票 ， 2 = 开票 （fcData.isInvoice：本地data的数据开票）
					if (this.fcData.isInvoice == 2) {
						// 再判断页面是否选择了专票还是普票。 invoiceType：1 = 普票 ， 2 = 专票（fcData.invoiceType：本地data的数据发票类型）
						if (this.fcData.invoiceType == 2) {
							// 是专票的话看税率是否有值（fcData.taxRate：本地data的数据税率）
							if (this.fcData.taxRate) {
								return ((purchasePrice || 0) / (1 + (this.fcData.taxRate) / 100)).toFixed(2)
							} else {
								return '--'
							}
						} else {
							return this.filteredData[0].purchasePrice.toFixed(2)
						}
					} else {
						return this.filteredData[0].purchasePrice.toFixed(2)
					}
				}
			} catch (e) {
				console.log(e)
			}

			// if (this.filteredData && this.filteredData[0].unitRanId == '1440879787235438593') { //主要供应商
			//   return ((purchasePrice || 0) / (1 + (this.filteredData[0].taxRate && this.filteredData[0].isInvoice == 2 && this.filteredData[0].invoiceType == 2 ? this.filteredData[0].taxRate : 0) / 100)).toFixed(2)
			// } else if (this.filteredData && this.filteredData[0].unitRanId == '1498270916314161153') { //非主要供应商
			//   return ((purchasePrice || 0) / (1 +
			//     (this.fcData.taxRate && this.fcData.isInvoice == 2 && this.fcData.invoiceType == 2 ? this.fcData.taxRate : 0)
			//     / 100)).toFixed(2)
			// } else {
			//   return undefined
			// }
		},
		// 选择物料之后的回调
		selected(row) {
			this.filteredData.push(row)
		},
		add(record) {
			if (!(record.selectedRows && record.selectedRows.length > 0)) {
				return this.$message.error('请先选择物料!')
			}
			this.visible = true
			this.$nextTick(() => {
				this.materialType = record.materialType
				this.poolType = record.poolType
				this.selectedList = [...record.selectedRows]
				console.log('已选物料', this.filteredData)
				this.type = record.orderType
				console.log('type,,,,,,,,,,,,,,', this.type)

				// 设定订单类型
				setTimeout(() => {
					this.form.setFieldsValue(record)
					this.createOrderNumber()
				}, 100)
				// 创建简单订单(无单出入库)时,record中包含选择的物料
				this.orderMaterials.length = 0
				this.orderMaterials.push(...record.selectedRows)
			})
		},

		// 打开弹框时候生成一个单号
		createOrderNumber() {
			var d = new Date()
			var year = d.getFullYear()
			var month = d.getMonth()
			month = month + 1 > 12 ? 1 : month + 1
			month = month > 9 ? month : "0" + month.toString()
			var day = d.getDate()
			day = day > 9 ? day : "0" + day.toString()
			var hour = d.getHours()
			hour = hour > 9 ? hour : "0" + hour.toString()
			var minute = d.getMinutes()
			minute = minute > 9 ? minute : "0" + minute.toString()
			var second = d.getSeconds()
			second = second > 9 ? second : "0" + second.toString()

			let num = parseInt(Math.random() * 100000).toString()
			// 如果随机数长度不够5位,则在后面补0,够5位为止
			for (let i = num.length; i < 5; i++) {
				num += '0'
			}

			let header = this.type == this.ORDER_TYPE_ENUM.inOrder.id ? 'WDRK' : this.type == this.ORDER_TYPE_ENUM.outOrder.id ? 'WDCK' : this.type == this.ORDER_TYPE_ENUM.purchaseOrder.id ? 'CG' : ''

			let scOrderNo = header + year + month + day + hour + minute + second + num

			this.form.setFieldsValue({ orderNumber: scOrderNo })
		},
		handleSubmit() {
			const { form: { validateFields } } = this
			if (!this.orderMaterials || this.orderMaterials.length == 0) {
				return this.$message.warning('请选择物料')
			}
			this.confirmLoading = true

			validateFields((errors, values) => {
				if (!errors) {
					// 创建采购单
					// 将池中的物料记录转成订单物料记录
					let orderMaterials = this.orderMaterials.map(values => {
						let {
							materialPoolId,
							materialId,
							number,
							purchasePrice,
							poolType,
							materialType,
							remark,
							status,
							createTime,
							createUser,
							updateTime,
							updateUser,
						} = values
						return {
							// orderMaterialId: '',
							// orderId: '',
							// sourceOrderId: '',
							// sourceOrderMaterialId: '',
							// bomId: '',
							materialId: materialId,
							number: number,
							purchasePrice,
							costPrice: this.getCostPrice(purchasePrice),
							// completedNumber: '',
							// executeStatus: '',
							// executeProgress: '',
							// file: '',
							remark,
							// markAbnormal: '',
							// status: '',
							// createTime: '',
							// createUser: '',
							// updateTime: '',
							// updateUser: '',
							materialPoolId: materialPoolId, //物料池ID，创建后删除用
						}
					})
					let myObj = {
						invoiceType: this.fcData.invoiceType ?? this.filteredData[0].invoiceType ?? undefined,
						isInvoice: this.fcData.isInvoice ?? this.filteredData[0].isInvoice ?? undefined,
						taxRate: this.fcData.taxRate ?? this.filteredData[0].taxRate ?? undefined,
						unitRanId: this.filteredData[0].unitRanId,
					}
					// 物料池ID,便于创建订单后删除
					let parameter = Object.assign({}, values, myObj, { orderMaterials })
					if (parameter.orderType == this.$businessEnum.ORDER_TYPE_ENUM.inOrder.id
						|| parameter.orderType == this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id) {
						addSimple(parameter).then((res) => {
							this.confirmLoading = false
							if (res.success) {
								this.$message.success('操作成功')
								this.handleCancel()
								this.$emit('ok', values)
							} else {
								this.$message.info('操作失败：' + res.message)
							}
						}).finally((res) => {
							this.confirmLoading = false
						})
					} else {
						// 在采购中心中,进行批量采购时会用到该方法
						addAllType(parameter).then((res) => {
							this.confirmLoading = false
							if (res.success) {
								this.$message.success('新增成功')
								this.handleCancel()
								this.$emit('ok', values)
							} else {
								this.$message.info('新增失败：' + res.message)
							}
						}).finally((res) => {
							this.confirmLoading = false
						})
					}
				} else {
					this.confirmLoading = false
				}
			})
		},
		handleCancel() {
			this.form.resetFields()
			this.visible = false
			this.resetFcData()
		},
		// upload
		handleFileListStringChange(fileListString) {
			this.form.setFieldsValue({ file: fileListString })
		},
	},
	created() {
	}
}
</script>

<style lang="less" scoped>
/deep/ .ant-form-item-children-icon {
	position: relative !important;
	left: 20px !important;
}
</style>
